// pages/dynamic/release.js
let axios = require("../../utils/util.js")
import VODUpload from '../../utils/aliyun-upload-sdk-1.0.0.min.js'
const app = getApp();
const recorderManager = wx.getRecorderManager() //录音
const innerAudioContext = wx.createInnerAudioContext() //播放语音
let md5 = require("../../utils/md5.js")
Page({
  /**
   * 页面的初始数据
   */
  data: {
    videos: {
      videoId: ''
    },
    showoverlay: false,
    voice_url: {
      voice_url: '', //语音
      voice_seconds: '', //语音时长
    }, //上传语音信息
    show: false,
    content: '',
    statusBarHeight: 0,
    checked: false, //显示城市
    satisfy: false,
    Selected: true, //参与话题
    queryBean: [], //话题
    headimg: "",
    NonText: 'init',
    max: '500',
    voiceText: {}, //文本信息

    timecount: '00:00',
    dianjiluzhi: true, //点击录制
    luzhizhong: false, //录制中
    shiting: false, //试听
    shiting_2: true,
    bofang_zhanting: false, //暂停
    tempFilePath: '', //录音文件流

    dianjiluzhi: true, //点击录制
    luzhizhong: false, //录制中
    shiting: false, //试听
    shiting_2: true,
    bofang_zhanting: false, //暂停
    Start_bottom: '开始录音',
    tempFilePath: '', //录音文件流

    minute: 0,
    second: 0,
    millisecond: 0,
    timecount: '00:00',
    init: null,
    isplay_radio: false,

    uploader: {}, //上传视频alliyun
  },
  //语音播放
  radio_play() {
    let that = this;
    if (that.data.isplay_radio) { //播放中状态
      console.log("暂停");
      that.setData({
        isplay_radio: !that.data.isplay_radio, //播放
      })
      innerAudioContext.pause()
      console.log(innerAudioContext);
    } else { //开始播放
      that.setData({
        isplay_radio: !that.data.isplay_radio, //播放
      })
      innerAudioContext.src = that.data.tempFilePath;
      innerAudioContext.play(); //开始播放 
      console.log(innerAudioContext.src);
    }
  },

  //确顶上传
  updata_andio() {
    console.log('点击确定');
    let that = this;
    let time = Date.parse(new Date());
    let data = {
      'voicefile': that.data.tempFilePath,
      'type': '2',
      'duration': that.data.minute * 60 + that.data.second * 1, //时长
      "userId": app.globalData.user_id,
      "token": app.globalData.userToken,
      "time": time,
    }
    let _token = this.encryption(data);
    wx.uploadFile({
      url: axios.testInterface + '/record/uploadVoice', //上传声音
      filePath: that.data.tempFilePath,
      voicefile: that.data.tempFilePath,
      name: "voicefile", //后台要绑定的名称
      //参数绑定
      formData: {
        'voicefile': that.data.tempFilePath,
        'type': '2',
        'duration': that.data.minute * 60 + that.data.second * 1, //时长
        "userId": app.globalData.user_id,
        "token": app.globalData.userToken,
        "time": time,
        'sign': md5.hexMD5(_token)
      },
      success: function (res) {
        var data = res.data
        const strToObj = JSON.parse(data)
        if (strToObj.status == '0') {
          console.log("录音上传成功", strToObj);
          wx.showToast({
            title: strToObj.text,
            icon: 'none',
            duration: 2000 //持续的时间
          })
          that.RecordingPopup(strToObj)
        } else {
          wx.showToast({
            title: strToObj.text,
            icon: 'none',
            duration: 3000 //持续的时间
          })
        }
      },
      fail: function (res) {
        console.log("。。录音保存失败。。", res);
        wx.showToast({
          title: "录音保存失败!!",
          icon: 'error',
        })
      }
    })
  },
  // 放大背景图
  preview(event) {
    wx.previewImage({
      current: event.currentTarget.dataset.src[0], // 当前显示图片的http链接
      urls: event.currentTarget.dataset.src[1] // 需要预览的图片http链接列表
    })
  },
  onChange({
    detail
  }) {
    // 需要手动对 checked 状态进行更新
    this.setData({
      checked: detail
    });
  },
  encryption(arys) {
    let that = this;
    var param = that.reverse(arys);
    var extra_str = "&wPQvCAOU$lbIyg9o2wVg0Dt1k^zy&SaX";
    if (Object.prototype.toString.call(param) !== '[object Object]') {
      return '';
    }
    let queryParam = '';
    for (let key in param) {
      if (param.hasOwnProperty(key)) {
        let value = param[key];
        // if(value){ 
        queryParam += that.toQueryPair(key, value);
        // }
      }
    }
    return queryParam.slice(1) + extra_str;
  },
  //对象转数组并倒序
  reverse(arys) {
    var newkey = Object.keys(arys).sort().reverse();
    var newObj = {};
    for (var i = 0; i < newkey.length; i++) {
      newObj[newkey[i]] = arys[newkey[i]];
    }
    return newObj;
  },
  //数组转字符串完成加密
  toQueryPair(key, value) {
    if (typeof value == 'undefined') {
      return `&${key}=`;
    }
    return `&${key}=${value}`;
  },
  //播放声音
  shiting() {
    this.setData({
      shiting_2: false,
      bofang_zhanting: true,
      Start_bottom: '点击暂停',
    })
    innerAudioContext.autoplay = true
    innerAudioContext.src = this.data.tempFilePath,
      innerAudioContext.onPlay(() => {
        console.log('开始播放')
      })
    innerAudioContext.onPause((res) => { //暂停播放
      console.log('暂停播放回调!');
    })
    innerAudioContext.onEnded((res) => { //结束播放
      this.setData({
        shiting_2: true,
        bofang_zhanting: false,
        Start_bottom: '点击试听',
      })
      innerAudioContext.stop()
      console.log("结束的回调");
    })
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })
  },
  timer() {
    var that = this;
    that.setData({
      millisecond: that.data.millisecond + 5
    })
    if (that.data.millisecond >= 100) {
      that.setData({
        millisecond: 0,
        second: that.data.second + 1
      })
    }
    if (that.data.second >= 60) {
      that.setData({
        second: 0,
        minute: that.data.minute + 1
      })
    }
    if (that.data.minute >= 60) {
      that.setData({
        minute: 0,
      })
    }
    that.setData({
      timecount: that.data.minute + ":" + that.data.second + ":" + that.data.millisecond
    })
  },
  Reset() {
    var that = this;
    clearInterval(that.data.init);
  },
  close_radio() {
    this.setData({
      minute: 0,
      second: 0,
      millisecond: 0,
      timecount: '00:00',
      NonText: 'init',
      tempFilePath: '',
    })
  },
  addRecord() {
    var pics = ''
    var topicIds = ''
    if (this.data.headimg.length > 0) {
      pics = this.data.headimg.join(';')
    }
    if (this.data.queryBean.length > 0) {
      var arr = this.data.queryBean.map(item => item.id);
      topicIds = arr.join(',')
    }
    let params = {
      content: encodeURI(this.data.content), //文字
      pics: pics, //图片
      voice: this.data.voice_url.voice_url, //语音
      voice_seconds: this.data.voice_url.voice_seconds, //语音时长
      videoId: this.data.videos.videoId, //视频参数
      showcity: this.data.checked ? '1' : '0', //城市
      topicIds: topicIds, //话题
    };
    axios.axios({
      url: "/record/addRecord",
      data: params
    }).then((res) => {
      if (res.data.status == 0) {
        this.setData({
          content: '',
          headimg: [],
          queryBean: [],
          voice_url: {},
          checked: false,
        })
        wx.switchTab({
          url: '/pages/dynamic/dynamic',
        })
      }
      console.log(res);
      wx.showToast({
        title: res.data.text,
        icon: 'none',
        duration: 3000
      })
    })
  },
  //开始录音的时候
  start_2: function () {
    this.start_time()
    this.setData({
      Start_bottom: '录音中',
      dianjiluzhi: false,
      luzhizhong: true,
    })
    const options = {
      duration: 60000, //指定录音的时长，单位 ms
      sampleRate: 16000, //采样率
      numberOfChannels: 1, //录音通道数
      encodeBitRate: 96000, //编码码率
      format: 'mp3', //音频格式，有效值 aac/mp3
      frameSize: 50, //指定帧大小，单位 KB
    }
    //开始录音
    recorderManager.start(options);
    recorderManager.onStart(() => {
      console.log('recorder start')
    });
    //错误回调
    recorderManager.onError((res) => {
      console.log(res);

    })
  },
  // 重录
  chong_recording() {
    this.setData({
      shiting: false,
      Start_bottom: '开始录音',
      dianjiluzhi: true,
    })
    clearInterval(this.data.init);
    this.setData({
      minute: 0,
      second: 0,
      millisecond: 0,
      timecount: '00:00'
    })
  },
  //停止录音
  stop_2() {
    this.stop_time(),
      this.setData({
        Start_bottom: '点击试听',
        luzhizhong: false,
        shiting: true,
      })
    recorderManager.stop();
    recorderManager.onStop((res) => {
      console.log('停止录音', res.tempFilePath)
      this.setData({
        tempFilePath: res.tempFilePath
      })
    })
  },
  RecordingPopup(status) {
    this.setData({
      show: !this.data.show,
    })
    if (!this.data.show) {
      this.setData({
        Start_bottom: '开始录音',
        shiting: false,
        dianjiluzhi: true,
        NonText: 'mp3',
        voice_url: status.result,
      })
      this.Reset(); //清空计时器
    }
  },
  //语音播放
  start(data) {
    let e = data.currentTarget.dataset.url
    console.log(e);
    this.setData({
      is_statys: !this.data.is_statys
    })
    if (this.data.is_statys) {
      innerAudioContext.src = e;
      innerAudioContext.play(); //开始播放 
    } else {
      console.log("暂停");
      innerAudioContext.pause()
    }
  },
  // 暂停
  zanting_() {
    innerAudioContext.pause()
    this.setData({
      shiting_2: true,
      bofang_zhanting: false,
      Start_bottom: '点击继续',
    })
  },
  // 暂停
  stop_time() {
    clearInterval(this.data.init);
  },
  start_time() {
    var that = this;
    clearInterval(that.data.init);
    that.setData({
      minute: 0,
      second: 0,
      millisecond: 0
    })
    that.data.init = setInterval(function () {
      that.timer()
    }, 50);
  },
  to_Select_topic() {
    wx.navigateTo({
      url: '/pages/dynamic/Select_topic',
    })
  },
  tab_back() {
    wx.navigateBack({
      delta: 1,
    })
  },
  // vioce_no() {
  //   this.setData({
  //     NonText: 'mp4'
  //   })
  //   this.chooseVideo()
  // },
  // 选择视频
  chooseVideo: function (e) {
    var that = this;
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      compressed: false,
      camera: 'back',
      success: function (res) {
        var file = {
          url: res.tempFilePath,
          coverUrl: res.thumbTempFilePath
        };
        that.setData({
          videos: file,
          NonText: 'mp4'
        });

        var uploader = that.data.uploader;
        var userData = '{"Vod":{}}'
        uploader.addFile(file, null, null, null, userData)

        that.data.uploader.startUpload();
      }
    })
  },
  removeVideo: function (event) {
    this.setData({
      videos: {},
      NonText: "init"
    });
  },
  inputs: function (e) {
    var content = e.detail.value;
    var len = parseInt(content.length);
    if (len > this.data.max) return;

    //检测是否含有表情
    // var regRule = /\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g;
    // if (content.match(regRule)) {
    //   content = content.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "");
    // }

    this.setData({
      content: content,
      currentWordNumber: len
    });
    if (this.data.currentWordNumber == 500) {
      wx.showModal({
        title: '提示',
        content: '您输入的文本内容已达上限',
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    wx.getSystemInfo({
      success: res => {
        let custom = wx.getMenuButtonBoundingClientRect();
        that.setData({
          statusBarHeight: res.statusBarHeight,
        })
      },
    });

    innerAudioContext.onPlay(() => { //开始播放
      console.log("开始的回调");
    })
    innerAudioContext.onPause((res) => { //暂停播放
      console.log('暂停播放回调!');
    })
    innerAudioContext.onEnded((res) => { //结束播放
      console.log("结束的回调");
      that.setData({
        isplay_radio: false,
      })
    })

    app.setWatcher(this);
  },

  watch: {
    content: {
      handler(newValue) {
        if (this.data.headimg.length > 0 || this.data.tempFilePath.length > 0 || newValue.length > 10 || this.data.videos.url) {
          this.setData({
            satisfy: true
          })
        } else {
          this.setData({
            satisfy: false
          })
        }
      },
      deep: true // 是否深度监听
    },
    headimg: {
      handler(newValue, oldvalue) {
        if (newValue.length > 0 || this.data.content.length > 10) {
          this.setData({
            satisfy: true
          })
        } else {
          this.setData({
            satisfy: false
          })
        }
      },
      deep: true
    },
    tempFilePath: {
      handler(newValue) {
        if (newValue.length > 0 || this.data.content.length > 10) {
          this.setData({
            satisfy: true
          })
        } else {
          this.setData({
            satisfy: false
          })
        }
      },
      deep: true // 是否深度监听
    },
    videos: {
      handler(newValue) {
        console.log(newValue);
        console.log(newValue.url);
        if (newValue.url || this.data.content.length > 10) {
          this.setData({
            satisfy: true
          })
        } else {
          this.setData({
            satisfy: false
          })
        }
      },
      deep: true // 是否深度监听
    },
  },
  splice_delet(data) {
    let index = data.currentTarget.dataset.index;
    this.data.queryBean.splice(index, 1);
    if (this.data.queryBean.length == 0) {
      this.setData({
        Selected: true
      })
    } else {
      this.setData({
        queryBean: this.data.queryBean,
        Selected: false
      })
    }
  },
  Tosatr_wx() {
    wx.showToast({
      title: '请完善内容',
      icon: 'none',
      debugger: 2000
    })
  },
  delet_image(data) {
    let index = data.currentTarget.dataset.index;
    this.data.headimg.splice(index, 1)
    this.setData({
      headimg: this.data.headimg
    })
    if (this.data.headimg.length == 0) {
      this.setData({
        NonText: 'init',
      })
    }
  },
  // 上传图片
  chooseImg() {
    var _this = this
    wx.chooseImage({
      count: 1,
      count: 6 - _this.data.headimg.length * 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        _this.setData({
          showoverlay: true
        })
        var tempFilePaths = res.tempFilePaths
        for (var i = 0; i < tempFilePaths.length; i++) { //循环上传多张image
          wx.uploadFile({
            url: axios.testInterface + '/record/uploadImg', //上传图片
            filePath: tempFilePaths[i],
            name: 'file',
            formData: {
              'type': '1'
            },
            success(res) {
              var data = res.data
              const strToObj = JSON.parse(data)
              // console.log(strToObj.result);
              _this.setData({
                NonText: "image",
                headimg: [..._this.data.headimg, strToObj.result],
                showoverlay: false,
              })
            }
          })
        }
      }
    })
  },
  onClickHide() {
    this.setData({
      showoverlay: false,
    })
  },
  //上传视频
  showPopup() {
    this.setData({
      show: true
    });
    let params = {};
    axios.axios({
      url: "/record/voiceText",
      data: params
    }).then((res) => {
      res.data.result.botton_color = "background:linear-gradient(180deg, " + res.data.result.top_color + "," + res.data.result.botton_color + ")"
      this.setData({
        voiceText: res.data.result
      })
    })
  },
  //关闭弹窗
  onClose() {
    this.setData({
      show: false
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

    var that = this;

    var uploader = new VODUpload({
      userId: '1866217700570151',
      timeout: 60000,
      region: "cn-shanghai",
      // 添加文件成功
      addFileSuccess: function (uploadInfo) {
        console.log("addFileSuccess" + JSON.stringify(uploadInfo))
      },
      // 开始上传
      onUploadstarted: function (uploadInfo) {
        console.log('文件开始上传...');
        console.log("onUploadStarted:" + JSON.stringify(uploadInfo))
        console.log(uploadInfo);

        let params = {
          format: 'MP4',
          source: 'record',
        };
        axios.axios({
          url: "/record/getUploadVideoUrl",
          data: params
        }).then((res) => {
          if (res.data.status == 0) {
            var akInfo = res.data.result;
            // uploader.setUploadAuthAndAddress(uploadInfo, akInfo.uploadAuth, akInfo.uploadAddress, akInfo.videoId);
            console.log(uploader.setUploadAuthAndAddress(uploadInfo, akInfo.uploadAuth, akInfo.uploadAddress, akInfo.videoId));
          }
        })

      },
      // 文件上传成功
      onUploadSucceed: function (uploadInfo) {
        console.log(uploadInfo)
        console.log(JSON.stringify(uploadInfo))
        console.log('文件上传成功!')
        let videos = 'videos.videoId';
        that.setData({
          [videos]: uploadInfo.videoId
        })
      },
      // 文件上传失败
      onUploadFailed: function (uploadInfo, code, message) {
        console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message)
        console.log('文件上传失败!')
        uploader.stopUpload();
      },
      // 取消文件上传
      onUploadCanceled: function (uploadInfo, code, message) {
        console.log(JSON.stringify(uploadInfo) + code + message)
        console.log('文件已暂停上传!')
        uploader.stopUpload();

      },
      // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
      onUploadProgress: function (uploadInfo, totalSize, progress) {
        var files;
        if (uploadInfo.isImage) {
          files = that.data.images;
        } else {
          files = that.data.videos;
        }
        console.log(files);

        // files.forEach((file, idx) => {
        //   if (file.url === uploadInfo.url) {
        //     file.progress = progress;
        //     if (uploadInfo.isImage) {
        //       that.setData({
        //         images: files
        //       })
        //     } else {
        //       that.setData({
        //         videos: files
        //       })
        //     }
        //   }
        // })


        console.log(JSON.stringify(uploadInfo) + "|" + totalSize + "|" + progress)
        // console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(progress * 100) + "%")
        var progressPercent = Math.ceil(progress * 100)
        console.log('文件上传中...' + progressPercent);
        wx.showToast({
          title: '文件上传中...' + progressPercent / 100 + '%',
          icon: 'none',
          duration: 5000
        })
        // $('#sts-progress').text(progressPercent)
        // $('#status').text('文件上传中...')

      },
      // 上传凭证超时
      onUploadTokenExpired: function (uploadInfo) {
        // // 如果是上传方式二即根据 STSToken 实现时，从新获取STS临时账号用于恢复上传
        // // 上传文件过大时可能在上传过程中 sts token 就会失效, 所以需要在 token 过期的回调中调用 resumeUploadWithSTSToken 方法
        // // 这里是测试接口, 所以我直接获取了 STSToken
        // $('#status').text('文件上传超时!')
        //
        // var stsUrl = 'http://demo-vod.cn-shanghai.aliyuncs.com/voddemo/CreateSecurityToken?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=67999yyuuuy&AppVersion=1.0.0'
        // $.get(stsUrl, function (data) {
        //     var info = data.SecurityTokenInfo
        //     var accessKeyId = info.AccessKeyId
        //     var accessKeySecret = info.AccessKeySecret
        //     var secretToken = info.SecurityToken
        //     var expiration = info.Expiration
        //     uploader.resumeUploadWithSTSToken(accessKeyId, accessKeySecret, secretToken, expiration)
        // }, 'json')
      },
      // 全部文件上传结束
      onUploadEnd: function (uploadInfo) {
        wx.showToast({
          title: '上传成功',
          icon: 'none',
          duration: 2000
        })
        console.log("文件上传完毕 onUploadEnd: uploaded all the files")
      }
    });

    this.setData({
      uploader: uploader
    });


  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1]
    if (currPage.data.queryBean.length > 0 && typeof currPage.data.queryBean == 'string') {
      // console.log(currPage.data.queryBean);
      this.setData({
        Selected: false,
        queryBean: JSON.parse(currPage.data.queryBean)
      })
    }
  },
  _getSuffix: function (filename) {
    var pos = filename.lastIndexOf('.')
    var suffix = ''
    if (pos != -1) {
      suffix = filename.substring(++pos)
    }
    return suffix;
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
